package com.fy.fyspace.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author fwq
 */
@Slf4j
@Component
public class RedisUtil {

  @Resource
  private RedisTemplate<String, Object> redisTemplate;

  private static final String AI_TASK_KEY_PREFIX = "ai:task:";

  /**
   * 保存AI任务信息
   *
   * @param taskId  任务ID
   * @param value   任务信息
   * @param timeout 过期时间(秒)
   */
  public void saveAiTask(String taskId, Object value, long timeout) {
    String key = AI_TASK_KEY_PREFIX + taskId;
    try {
      redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
      log.info("保存AI任务信息成功: taskId={}", taskId);
    } catch (Exception e) {
      log.error("保存AI任务信息失败: taskId={}, error={}", taskId, e.getMessage(), e);
      throw new RuntimeException("保存AI任务信息失败", e);
    }
  }

  /**
   * 获取AI任务信息
   *
   * @param taskId 任务ID
   * @return 任务信息
   */
  public Object getAiTask(String taskId) {
    String key = AI_TASK_KEY_PREFIX + taskId;
    try {
      Object value = redisTemplate.opsForValue().get(key);
      log.info("获取AI任务信息: taskId={}, exists={}", taskId, value != null);
      return value;
    } catch (Exception e) {
      log.error("获取AI任务信息失败: taskId={}, error={}", taskId, e.getMessage(), e);
      throw new RuntimeException("获取AI任务信息失败", e);
    }
  }

  /**
   * 删除AI任务信息
   *
   * @param taskId 任务ID
   */
  public void deleteAiTask(String taskId) {
    String key = AI_TASK_KEY_PREFIX + taskId;
    try {
      redisTemplate.delete(key);
      log.info("删除AI任务信息成功: taskId={}", taskId);
    } catch (Exception e) {
      log.error("删除AI任务信息失败: taskId={}, error={}", taskId, e.getMessage(), e);
      throw new RuntimeException("删除AI任务信息失败", e);
    }
  }

  /**
   * 更新AI任务信息的过期时间
   *
   * @param taskId  任务ID
   * @param timeout 过期时间(秒)
   */
  public void updateAiTaskExpire(String taskId, long timeout) {
    String key = AI_TASK_KEY_PREFIX + taskId;
    try {
      redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
      log.info("更新AI任务过期时间成功: taskId={}, timeout={}s", taskId, timeout);
    } catch (Exception e) {
      log.error("更新AI任务过期时间失败: taskId={}, error={}", taskId, e.getMessage(), e);
      throw new RuntimeException("更新AI任务过期时间失败", e);
    }
  }
}